<template>
    <div>
        <div class="pt-26px table-container">
            <el-table :data="props.tableData" :default-sort="{ prop: 'searchTotal', order: 'descending' }"
                :row-key="row => row.ID" :reserve-selection="true" @selection-change="handleSelectionChange"
                class="w-full">
                <el-table-column type="selection" label="" align="center" width="60" />
                <el-table-column label="产品图片" align="center" width="150">
                    <template #default="scope">
                        <el-tooltip placement="right" effect="light" v-if="scope.row.InforPicTure">
                            <div class="flex flex-center w-80px h-80px m-0 m-auto" >
                                <a :href="'#/b2b/product/detail/' + scope.row.ID"><img :src="scope.row.InforPicTure"
                                :alt="scope.row.InforTitle"></a>
                            </div>
                            <template #content><img :src="scope.row.InforPicTure"
                                :alt="scope.row.InforTitle" class="w-200px w-200px"></template>
                        </el-tooltip>
                        <div class="flex flex-center w-80px h-80px no-img" v-else>
                            暂无图片
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="InforTitle" label="产品名称" align="center">
                    <template #default="scope">
                        <el-link :href="'#/b2b/product/detail/' + scope.row.ID">{{ scope.row.InforTitle }}</el-link>
                    </template>
                </el-table-column>
                <el-table-column align="center" width="180">
                    <template #header>
                        <div>主关键词<el-tooltip placement="top" content="不建议使用带字母或数字的关键词">
                                <svg-icon size="14px" icon-class="information-2-fill"
                                    class="ml-5px text-gray"></svg-icon>
                            </el-tooltip></div>
                    </template>
                    <template #default="scope">
                        <template v-if="scope.row.Keyword.length > 0">
                            {{ scope.row.Keyword }}
                        </template>
                        <template v-else>
                            <el-button type="primary" size="small" plain @click="handleAddKeyword(scope.row.ID)">添加关键词</el-button>
                        </template>
                    </template>
                </el-table-column>
                <el-table-column prop="time" label="添加时间" align="center" width="180">
                    <template #default="scope">
                        {{ formatDate(scope.row.CreateDate) }}
                    </template>
                </el-table-column>
                <el-table-column v-if="props.tab === 4" prop="LowerShelfDate" label="下架时间" align="center" width="180">
                    <template #default="scope">
                        {{ formatDate(scope.row.LowerShelfDate) }}
                    </template>
                </el-table-column>
                <el-table-column v-if="props.tab === 3" prop="FaillRemark" label="失败原因" align="center" width="200">
                    <template #default="scope">
                        <el-button :icon="View" type="primary" text
                            @click="handleView(scope.row.FaillRemark)">查看原因</el-button>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="280">
                    <template #default="scope">
                        <el-button v-if="props.tab === 4" :icon="Sell" type="primary" text
                            @click="handleUp(scope.row)">上架</el-button>
                        <el-button :icon="Edit" type="primary" text class="!ml-0"
                            @click="handleEdit(scope.row.ID)">修改</el-button>
                        <el-button :icon="Delete" type="danger" text class="!ml-0"
                            @click="handleDelete(scope.row.ID)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="pt-26px pl-26px pr-26px pb-26px page-container flex justify-between items-center">
            <div class="flex items-center text-12px">
                已选 {{ selectionData.length }} 条数据 <el-button v-if="props.tab === 4" type="primary" text size="small"
                    class="ml-12px" @click="handleBatchUp">批量上架</el-button><el-button type="danger" text size="small"
                    class="ml-12px" @click="handleBatchDelete">批量删除</el-button>
            </div>
            <Pagination v-if="tableData.length > 0" v-model:total="page.total" v-model:page="queryParams.curPage"
                v-model:limit="queryParams.pageSizes" @pagination="handleQuery" />
        </div>
        <ConfirmDialog ref="confirmDialogRef" message="您确定要删除该条数据吗？" @confirm="onConfirmDelete" />
        <OnTheShelves v-model:isOnTheShelves="isOnTheShelves" :productId="productId" @closeDialog="handleClose" />
    </div>
</template>

<script setup lang="ts">
import { Delete, Edit, Sell, View, WarningFilled, SuccessFilled } from '@element-plus/icons-vue'
import Pagination from '@/components/Pagination/index.vue'
import ConfirmDialog from '@/components/ConfirmDialog/index.vue'
import OnTheShelves from './OnTheShelves.vue'
import { dateFormat } from '@/utils/date'
import { confirmMessageBox } from '@/utils/elMessageBox'
import { deleteProductApi, batchDeleteProductApi, batchUpProductApi } from '@/api/b2b'

const props = defineProps({
    tableData: {
        type: Array,
        default: () => []
    },
    tab: {
        type: Number,
        default: ''
    },
    page: {
        type: Object,
        default: () => { }
    }
})

const emit = defineEmits(['update:data'])

const router = useRouter()

const confirmDialogRef = ref()

const formatDate = computed(() => {
    return function (data: string) {
        return dateFormat(data, 'YYYY-MM-DD')
    }
})

const loading = ref(true);

const queryParams = reactive({
    curPage: props.page.curPage,
    pageSizes: props.page.pageSizes,
    limit: props.page.limit,
});

const selectionData = ref([])

const productId = ref()

const isOnTheShelves = ref(false)

async function handleDelete(id: string) {
    confirmDialogRef.value?.showConfirm()
    productId.value = id
}

function handleSelectionChange(rows: any) {
    selectionData.value = rows.map((row: any) => row.ID)
}

function handleQuery() {
    loading.value = true
    emit('update:data', queryParams)
}

function handleBatchDelete() {
    if (!selectionData.value.length) {
        confirmMessageBox(WarningFilled, '请选择多个要批量删除的产品？')
    } else {
        confirmMessageBox(WarningFilled, '您确定要批量删除的产品？', '','', async () => {
            const res = await batchDeleteProductApi({
                proids: selectionData.value
            })
            if (res.code === 200) {
                ElMessage({
                    type: 'success',
                    message: '删除成功!',
                })
                selectionData.value = []
                emit('update:data', queryParams)
            }
        }, () => {
            ElMessage({
                type: 'info',
                message: '已取消删除',
            })
        })
    }
}

async function onConfirmDelete() {
    const res = await deleteProductApi({
        id: productId.value
    })
    if (res.code === 200) {
        ElMessage({
            type: 'success',
            message: '删除成功!',
        })
        productId.value = ''
        emit('update:data', queryParams)
    }
}

function handleEdit(id: string) {
    router.push({
        path: '/b2b/product/edit/' + id
    })
}

function handleView(str: string) {
    confirmMessageBox(WarningFilled, str)
}

async function handleClose() {
    isOnTheShelves.value = false
    productId.value = ''
    await handleQuery()
}

async function handleUp(value: any) {
    //1、判断服务套餐是否到期(403)
    //2、显示弹窗：确认上架
    //3、判断是否有关键词

    if(value.Keyword.length === 0){
        confirmMessageBox(WarningFilled, '请添加该产品的关键词', '','', () => { 
            router.push({
                path: '/b2b/product/edit/' + value.ID,
                query: {
                    step: 1
                }
            })
        })
    }else{
        isOnTheShelves.value = true
        productId.value = value.ID
    }
}

async function handleBatchUp() {
    if (!selectionData.value.length) {
        confirmMessageBox(WarningFilled, '请选择多个要批量上架的产品')
    } else {
        try{
            const res = await batchUpProductApi({
                proids: selectionData.value
            })
            if (res.code === 200) {
                confirmMessageBox(SuccessFilled, res.message, '','', async () => {
                    selectionData.value = []
                    await handleQuery()
                })
            }
        }catch(error:any){
            console.log(error)
        }
    }
}

function handleAddKeyword(id:number){
    router.push({
        path: '/b2b/product/edit/' + id,
        query: {
            step: 1
        }
    })
}
</script>

<style scoped>

</style>